<template>
  <div class="c2c-my-trades">
    <div class="page-header">
      <h2 class="page-title">我的交易</h2>
      <p class="page-subtitle">管理我参与的C2C交易</p>
    </div>
    
    <el-card class="trades-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><ShoppingCart /></el-icon>
          <span>我的交易</span>
        </div>
      </template>
      
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="searchForm" style="margin-bottom: 20px">
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部" clearable>
            <el-option label="待付款" value="pending" />
            <el-option label="已付款" value="paid" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadTrades">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 交易列表 -->
      <el-table :data="trades" style="width: 100%" v-loading="loading">
        <el-table-column prop="tradeId" label="交易ID" width="120" />
        <el-table-column prop="orderType" label="订单类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.orderType === 'buy' ? 'success' : 'warning'">
              {{ row.orderType === 'buy' ? '买单' : '卖单' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currency" label="币种" width="100" />
        <el-table-column prop="amount" label="数量" width="120">
          <template #default="{ row }">
            {{ formatAmount(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价" width="120">
          <template #default="{ row }">
            ¥{{ formatAmount(row.price) }}
          </template>
        </el-table-column>
        <el-table-column prop="total" label="总额" width="120">
          <template #default="{ row }">
            ¥{{ formatAmount(row.amount * row.price) }}
          </template>
        </el-table-column>
        <el-table-column prop="role" label="我的角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'buyer' ? 'primary' : 'success'">
              {{ row.role === 'buyer' ? '买家' : '卖家' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="text"
              size="small"
              @click="viewTradeDetail(row)"
            >
              详情
            </el-button>
            <el-button
              v-if="row.status === 'pending' && row.role === 'buyer'"
              type="primary"
              size="small"
              @click="handlePay(row)"
            >
              确认付款
            </el-button>
            <el-button
              v-if="row.status === 'paid' && row.role === 'seller'"
              type="success"
              size="small"
              @click="handleComplete(row)"
            >
              确认收款
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              type="danger"
              size="small"
              @click="handleCancel(row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadTrades"
        @current-change="loadTrades"
        style="margin-top: 20px"
      />
    </el-card>
    
    <!-- 交易详情对话框 -->
    <el-dialog v-model="detailVisible" title="交易详情" width="900px">
      <el-tabs v-if="currentTrade" v-model="activeTab">
        <el-tab-pane label="交易信息" name="info">
          <el-descriptions :column="2" border>
        <el-descriptions-item label="交易ID">
          {{ currentTrade.tradeId }}
        </el-descriptions-item>
        <el-descriptions-item label="订单类型">
          <el-tag :type="currentTrade.orderType === 'buy' ? 'success' : 'warning'">
            {{ currentTrade.orderType === 'buy' ? '买单' : '卖单' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="币种">
          {{ currentTrade.currency }}
        </el-descriptions-item>
        <el-descriptions-item label="数量">
          {{ formatAmount(currentTrade.amount) }}
        </el-descriptions-item>
        <el-descriptions-item label="单价">
          ¥{{ formatAmount(currentTrade.price) }}
        </el-descriptions-item>
        <el-descriptions-item label="总额">
          ¥{{ formatAmount(currentTrade.amount * currentTrade.price) }}
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">
          {{ currentTrade.paymentMethod }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentTrade.status)">
            {{ getStatusLabel(currentTrade.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="我的角色">
          <el-tag :type="currentTrade.role === 'buyer' ? 'primary' : 'success'">
            {{ currentTrade.role === 'buyer' ? '买家' : '卖家' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="对方用户ID">
          {{ currentTrade.role === 'buyer' ? currentTrade.sellerId : currentTrade.buyerId }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ currentTrade.remark || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDate(currentTrade.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentTrade.paidAt" label="付款时间" :span="2">
          {{ formatDate(currentTrade.paidAt) }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentTrade.completedAt" label="完成时间" :span="2">
          {{ formatDate(currentTrade.completedAt) }}
        </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="聊天" name="chat">
          <div style="height: 500px">
            <ChatBox
              v-if="currentTrade"
              :context-id="currentTrade.tradeId"
              :receiver-id="currentTrade.role === 'buyer' ? currentTrade.sellerId : currentTrade.buyerId"
              :receiver-username="currentTrade.role === 'buyer' ? currentTrade.sellerUsername : currentTrade.buyerUsername"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button
          v-if="currentTrade && currentTrade.status === 'pending' && currentTrade.role === 'buyer'"
          type="primary"
          @click="handlePay(currentTrade)"
        >
          确认付款
        </el-button>
        <el-button
          v-if="currentTrade && currentTrade.status === 'paid' && currentTrade.role === 'seller'"
          type="success"
          @click="handleComplete(currentTrade)"
        >
          确认收款
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 完成交易对话框 -->
    <el-dialog v-model="completeVisible" title="确认收款" width="500px">
      <el-form :model="completeForm" label-width="100px">
        <el-form-item label="交易ID">
          {{ completeForm.tradeId }}
        </el-form-item>
        <el-form-item label="交易金额">
          ¥{{ formatAmount(completeForm.amount * completeForm.price) }}
        </el-form-item>
        <el-form-item label="备注（可选）">
          <el-input
            v-model="completeForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="completeVisible = false">取消</el-button>
        <el-button type="success" :loading="completeLoading" @click="confirmComplete">
          确认收款
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ShoppingCart } from '@element-plus/icons-vue'
import { c2cApi } from '../api/c2c'
import { useAuthStore } from '../store/auth'
import ChatBox from '../components/ChatBox.vue'

const authStore = useAuthStore()
const currentUserId = computed(() => authStore.userInfo?.id || '')

const loading = ref(false)
const trades = ref<any[]>([])
const detailVisible = ref(false)
const currentTrade = ref<any>(null)
const completeVisible = ref(false)
const completeLoading = ref(false)
const activeTab = ref('info')

const searchForm = reactive({
  status: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

const completeForm = reactive({
  tradeId: '',
  amount: 0,
  price: 0,
  remark: ''
})

onMounted(() => {
  loadTrades()
})

const loadTrades = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      pageSize: pagination.pageSize
    }
    if (searchForm.status) params.status = searchForm.status
    
    const result = await c2cApi.getTrades(params)
    const tradesList = result.list || result.trades || []
    
    // 标记当前用户的角色
    trades.value = tradesList.map((trade: any) => {
      const role = trade.buyerId === currentUserId.value ? 'buyer' : 'seller'
      return { ...trade, role }
    })
    
    pagination.total = result.total || 0
  } catch (error: any) {
    ElMessage.error(error.message || '加载交易失败')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  searchForm.status = ''
  pagination.page = 1
  loadTrades()
}

const viewTradeDetail = async (trade: any) => {
  try {
    const detail = await c2cApi.getTradeDetail(trade.tradeId)
    const role = detail.buyerId === currentUserId.value ? 'buyer' : 'seller'
    currentTrade.value = { ...detail, role }
    detailVisible.value = true
  } catch (error: any) {
    ElMessage.error(error.message || '获取交易详情失败')
  }
}

const handlePay = async (trade: any) => {
  try {
    await ElMessageBox.confirm(
      `确认已付款？\n交易金额: ¥${formatAmount(trade.amount * trade.price)}\n支付方式: ${trade.paymentMethod}\n\n请确保您已经完成付款操作。`,
      '确认付款',
      {
        confirmButtonText: '确认已付款',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await c2cApi.payTrade(trade.tradeId)
    ElMessage.success('付款确认成功！等待卖家确认收款')
    loadTrades()
    detailVisible.value = false
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '确认付款失败')
    }
  }
}

const handleComplete = (trade: any) => {
  completeForm.tradeId = trade.tradeId
  completeForm.amount = trade.amount
  completeForm.price = trade.price
  completeForm.remark = ''
  completeVisible.value = true
}

const confirmComplete = async () => {
  try {
    await ElMessageBox.confirm(
      `确认已收到付款？\n交易金额: ¥${formatAmount(completeForm.amount * completeForm.price)}\n确认后将完成交易，币将转给买家。`,
      '确认收款',
      {
        confirmButtonText: '确认已收款',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    completeLoading.value = true
    await c2cApi.completeTrade(completeForm.tradeId, completeForm.remark)
    ElMessage.success('交易已完成！')
    completeVisible.value = false
    detailVisible.value = false
    loadTrades()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '完成交易失败')
    }
  } finally {
    completeLoading.value = false
  }
}

const handleCancel = async (trade: any) => {
  try {
    await ElMessageBox.confirm(
      `确认取消交易 ${trade.tradeId}？取消后无法恢复。`,
      '确认取消交易',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await c2cApi.cancelTrade(trade.tradeId)
    ElMessage.success('交易已取消')
    loadTrades()
    detailVisible.value = false
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '取消交易失败')
    }
  }
}

const formatAmount = (value: number) => {
  return value.toFixed(4)
}

const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

const getStatusTagType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'warning',
    paid: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return map[status] || ''
}

const getStatusLabel = (status: string) => {
  const map: Record<string, string> = {
    pending: '待付款',
    paid: '已付款',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}
</script>

<style scoped>
.c2c-my-trades {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.trades-card {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 18px;
  color: #409eff;
}
</style>

